﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using ImageTools;
using System.IO;
using ImageTools.IO.Png;
using System.Windows.Resources;

namespace GeoVision.BingMap.Windows
{
    public partial class ImageDialogWindow : ChildWindow
    {
        string BingUri { get; set; }
        public ImageDialogWindow(string imgUri)
        {
            InitializeComponent();
            BingUri = imgUri;
        }

        public void InitImage()
        {
            WebClient wc = new WebClient();
            wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
            wc.OpenReadAsync(new Uri(BingUri), UriKind.Absolute);
            wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
        }
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog
            {
                Filter = "PNG Files (*.png)|*.png",
                DefaultExt = ".png",
                FilterIndex = 1
            };

            if ((bool)sfd.ShowDialog())
            {
                var img = bitmap.ToImage();
                var encoder = new PngEncoder();
              
                using (Stream str= sfd.OpenFile())
                {
                    encoder.Encode(img, str);
                    str.Close();
                }
            }
        }
        

        private void ChildWindow_Loaded(object sender, RoutedEventArgs e)
        {
           
        }
        WriteableBitmap bitmap;
        void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            xbusy.IsBusy = true;
            xbusy.BusyContent = string.Format("Downloading %{0}, Byte Received {1}", e.ProgressPercentage, e.BytesReceived);
        }
        void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                StreamResourceInfo sri = new StreamResourceInfo(e.Result as Stream, null);
                BitmapImage imgsrc = new BitmapImage();
                imgsrc.SetSource(sri.Stream);
                ctlBingImage.Source = imgsrc;
                bitmap = new WriteableBitmap((BitmapSource)ctlBingImage.Source);
                xbusy.IsBusy = false;
            }
        }
    }
}

